<script setup lang="ts">
definePageMeta({
  title:'找回密码',
  layout:'w1200'
})
import type {FormInstance, FormRules} from "element-plus";
import {useCountDown} from "~/hooks";
const {data:random,refresh}=await useServerGet('/tools/getRandomCode')
const {countDown,restart,isRunning,stop}=useCountDown(120)
const active=ref(1)
const formRef=ref<FormInstance>()
const formRules=reactive<FormRules>({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {validator:(rule, value, callback)=>{
      if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)){
        callback(new Error('邮箱格式不正确'))
      }else{
        callback()
      }
    },trigger:'blur'
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
  random_code: [
    { required: true, message: '请输入随机码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  password1: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    {validator:(rule, value, callback)=>{
        if(value!==form.password){
          callback(new Error('两次密码不一致'))
        }else{
          callback()
        }
      },trigger:'blur'
    }
  ],
})
const form=reactive({
  email:'',
  code:'',
  password:'',
  password1:'',
  random_code:'',
})
const isSuccess=ref(false)
const sendCode=()=>{
  formRef.value?.validateField(['email'],async (valid,invalidFields) => {
    if (valid) {
      const {data,code}=await usePost('/user/sendSms', {email:form.email,});
      if(code==200){
        restart()
      }
    } else {
      showFieldsError(invalidFields)
      return false;
    }
  });

}
const submit=()=>{
  if(formRef.value){
    let fields=[]
    let url=''
    if(active.value==1){
      fields=['email','random_code']
      url='/user/sendMail'
    }else if(active.value==2){
      fields=['email','code','password','password1']
      url='/user/resetPassword'
    }else{
      fields=[]
    }
      formRef.value?.validateField(fields,async (valid, invalidFields)=>{
        if(valid){
          const {data,code}=await usePost(url,form);
            if(code===200){
              if(active.value==2){
                isSuccess.value=true
                active.value=3
                formRef.value?.clearValidate()
                formRef.value?.resetFields()
                stop();
              }else{
                active.value=active.value+1
                restart();
              }
            }
        }
      })
  }
}
const router=useRouter()
const login=useLoginStore()
const goLogin=()=>{
  router.push('/index.html')
  login.setVisible(true)
}
</script>

<template>
  <el-card class="p-4 m-4">
        <el-divider content-position="center" orientation="left">找回密码</el-divider>
        <div class="w-[800px] mx-auto my-20">
          <el-steps class="w-full flex justify-between" :active="active" align-center>
            <el-step title="步骤 1" description="填写找回邮箱" />
            <el-step title="步骤 2" description="修改密码" />
            <el-step title="步骤 3" description="找回成功" />
          </el-steps>
          <el-form :model="form" :rules="formRules" ref="formRef" class="w-[400px] mx-auto pt-20 pb-20">
            <template v-if="active==1">
              <el-form-item prop="email">
                <el-input v-model="form.email" clearable placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item prop="random_code">
                <div class="flex w-full">
                  <el-input v-model="form.random_code" class="w-3/5 h-7" clearable placeholder="请输入随机码"></el-input>
                  <img :src="random?.data?.random_code_img" class="h-10 ml-2" @click="refresh" alt="随机码"/>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submit" class="w-full">下一步</el-button>
              </el-form-item>
            </template>
           <template v-if="active==2">
             <p class="text-red-400 text-center pb-4">邮箱验证码已发送注意查收！！！</p>
             <el-form-item prop="code">
               <div class="flex w-full">
                 <el-input v-model="form.code" class="w-2/3" placeholder="请输入验证码" clearable></el-input>
                 <el-button type="primary" class="ml-2" @click="sendCode" :disabled="isRunning">{{isRunning?`${countDown}s`:'获取验证码'}}</el-button>
               </div>
             </el-form-item>
             <el-form-item prop="password">
               <div class="flex w-full">
                 <el-input type="password" v-model="form.password" clearable placeholder="请输入新密码"></el-input>
               </div>
             </el-form-item>
             <el-form-item prop="password1">
               <el-input type="password" v-model="form.password1" clearable placehold="请输入确认密码"></el-input>
             </el-form-item>
             <el-form-item>
               <div class="grid-cols-[50px_1fr] grid gap-2 w-full">
                 <el-button @click="()=>active=active-1" class="w-full">上一步</el-button><el-button type="primary" @click="submit" class="w-full">提交</el-button>
               </div>

             </el-form-item>
           </template>
            <template v-if="active==3">
              <el-form-item>
                <div class="flex w-full text-center mx-auto">
                  <div v-if="isSuccess" class="text-[var(--el-color-primary)] mx-auto"><ElIconSuccessFilled />成功找回密码</div>
                  <div v-else class="text-red-400 mx-auto"><ElIconFailed />找回密码失败</div>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="goLogin" class="w-full px-8">去登陆首页登录</el-button>
              </el-form-item>
            </template>
          </el-form>
        </div>
      </el-card>

</template>

<style scoped lang="scss">

</style>